package com.gdk.ksoft.assembly.dialog;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.constants.GoodsTypeConstant;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.ui.works.models.FworkGoodsOrderModel;
import com.gdk.ksoft.assembly.dbhelper.FworkDbHelper;
import com.gdk.ksoft.assembly.utils.extensions.ControlUtils;
import com.gdk.ksoft.assembly.utils.extensions.FormatUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * Created by hel on 2014-11-27.
 * 新增单品的Dialog
 */
public class FixSingleProductDialog extends Dialog {

    /**
     * 值改变监听
     */
    public interface OnValueChangedListener{
        public void onValueChanged();
    }

    @ViewInject(R.id.dialog_fixsingleProduct_txtGoodsName)private TextView txtGoodsName;//商品名字
    @ViewInject(R.id.dialog_fixsingleProduct_txtGoodsGg)private TextView txtGoodsGg;//商品规格
    @ViewInject(R.id.dialog_fixsingleProduct_txtGoodsCode)private TextView txtGoodsCode;//商品条码
    @ViewInject(R.id.dialog_fixsingleProduct_imgIcon)private ImageView imgGoodsIcon;//商品图标
    @ViewInject(R.id.dialog_fixsingleProduct_txtGoodsStock)private TextView txtGoodsStock;//商品库存
    @ViewInject(R.id.dialog_fixsingleProduct_etPiece)private EditText etPiece;//件数
    @ViewInject(R.id.dialog_fixsingleProduct_etBottle)private EditText etBottle;//瓶数
    @ViewInject(R.id.dialog_fixsingleProduct_txtMaxModule)private TextView txtMaxModule;//最大单位
    @ViewInject(R.id.dialog_fixsingleProduct_txtMinModule)private TextView txtMinModule;//最小单位
    @ViewInject(R.id.dialog_fixsingleProduct_etPiecePrice)private EditText etPiecePrice;//件价
    @ViewInject(R.id.dialog_fixsingleProduct_txtPrice)private TextView txtPrice;//单价
    @ViewInject(R.id.dialog_fixsingleProdct_txtMoney)private TextView txtMoney;//金额
    @ViewInject(R.id.dialog_fixsingleProduct_txtSpecial)private TextView txtSpecial;//特殊选择
    @ViewInject(R.id.dialog_fixsingleProdct_etSummary)private EditText etSummary;//说明文字

    private FworkGoodsOrderModel model = null;//商品信息
    private OnValueChangedListener listener;
    private View.OnFocusChangeListener flistener;
    private TextWatcher textWatcher;
    private DbUtils dbUtils;//数据库操作对象

    public FixSingleProductDialog(Context context, FworkGoodsOrderModel model) {
        super(context,R.style.WindowDialogTheme);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        View rootView = View.inflate(context, R.layout.dialog_fixsingle_product,null);
        setContentView(rootView);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.horizontalMargin = 5f;
        getWindow().setAttributes(lp);
        ViewUtils.inject(this, rootView);
        dbUtils = SQLiteUtils.getInstance(context).getDbUtils();
        this.model = model;//赋值参数
        initDialog();//初始化基本
        initDialogInfo(context);//初始化页面信息

    }

    /**
     * 通知其他地方本界面数据发生了变化
     * @param listener
     */
    public void setOnValueChangedListener(OnValueChangedListener listener){
        this.listener = listener;//设置值得监听事件
    }

    /**
     * 初始化界面操作
     */
    public void initDialog(){
        flistener = new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                changeArguments();//没有焦点的时候计算
            }
        };
        textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                changeArguments();//文本改变以后计算一次
            }
        };
        txtSpecial.setOnFocusChangeListener(flistener);
        etPiecePrice.setOnFocusChangeListener(flistener);
        etPiecePrice.addTextChangedListener(textWatcher);
        etPiece.setOnFocusChangeListener(flistener);
        etPiece.addTextChangedListener(textWatcher);
        etBottle.setOnFocusChangeListener(flistener);
        etBottle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                if(!checkSingleNum()) return;
                changeArguments();//文本改变以后计算一次
            }
        });
    }

    /**
     * 初始化对话框显示数据
     * @param context
     */
    public void initDialogInfo(final Context context){
        txtGoodsName.setText(model.goodsInfo.mc);//获取商品规格
        txtGoodsGg.setText(model.goodsInfo.gg + model.goodsInfo.dw);//获取商品规格
        txtGoodsCode.setText(model.goodsInfo.tm);//获取商品条码
        etBottle.setText(model.singleNum+"");//获取单品数量
        etPiece.setText(model.pieceNum+"");//获取件数量
        etPiecePrice.setText(model.finalPrice+"");//获取最总单价定义
        txtMaxModule.setText(model.goodsModuleInfo.jldwmc);
        txtMinModule.setText(model.goodsInfo.dw);
        float leftStock = model.goodsInfo.kc - model.goodsInfo.xl;
        txtGoodsStock.setText("库存："+((int)(leftStock/model.goodsModuleInfo.hsgx))+model.goodsModuleInfo.jldwmc
                +((int)(leftStock%model.goodsModuleInfo.hsgx))+model.goodsInfo.dw);
        model.goodsModuleInfo.dj = model.finalPrice;//当前应该显示处理的单价
        txtPrice.setText("单价"+FormatUtils.exactNumber(model.finalPrice/model.goodsModuleInfo.hsgx,"0.00")+"元");
        etSummary.setText(model.noteInfomation);//获取备注信息
        txtMoney.setText(FormatUtils.exactNumber(model.totalMoney,"0.00")+"元");//获取金额数
        txtSpecial.setText(GoodsTypeConstant.getGoodsType().get(model.goodsType));//获取商品类种
        if(model.isCanChangePrice != 1){//不能修改价格数据，冻结控件
            txtPrice.setEnabled(false);
            etPiecePrice.setEnabled(false);
        }
        new BitmapUtils(context).configDefaultLoadFailedImage(R.drawable.ic_default_goods)
                .configDefaultLoadingImage(R.drawable.ic_default_goods)
                .display(imgGoodsIcon, SystemData.BASE_URL + model.goodsInfo.slt);//获取商品图片
    }

    /**
     * 件价是否可用
     * @return
     */
    public boolean isPiecePriceAvaliable(){
        String price = ControlUtils.getNumberStringFromTextView(etPiecePrice);
        float minPrice = (float)SystemData.SaleManPower * model.goodsModuleInfo.dj;
        if(Float.compare(Float.parseFloat(price),0) == 0) return true;//价格为0时可用
        if(Float.compare(Float.parseFloat(price),minPrice )<0) {
            Toast.makeText(getContext(), "对不起，价格小于预期值"
                    + FormatUtils.exactNumber(minPrice,"0.00")+"元!", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 检测散数数据
     * @return
     */
    public boolean checkSingleNum(){
        String etBottleVal = ControlUtils.getNumberStringFromTextView(etBottle);
        String etPieceVal = ControlUtils.getNumberStringFromTextView(etPiece);
        int bottleNum = Integer.valueOf(etBottleVal);
        int pieceNum = Integer.valueOf(etPieceVal);
        if (model.goodsInfo.mjsl <= Math.abs(bottleNum)){
            Toast.makeText(getContext(),"散数数量不能超过规格规定!",Toast.LENGTH_SHORT).show();
            etBottle.setFocusable(true);
            return false;
        }
        if((bottleNum>=0 && pieceNum>=0) ||(bottleNum<=0 && pieceNum<=0))
            return true;
        else {
            Toast.makeText(getContext(),"件数或散数应有相同的符号!",Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    /**
     * 检测参数的有效性
     * @return
     */
    public void changeArguments(){
        String pieceNum = ControlUtils.getNumberStringFromTextView(etPiece);
        String bottleNum = ControlUtils.getNumberStringFromTextView(etBottle);
        String piecePrice = ControlUtils.getNumberStringFromTextView(etPiecePrice);
        if(txtSpecial.getText().toString().trim().equals(GoodsTypeConstant.GOODS_TYPE_TEXTS[0])) {
            int pieceVal = Integer.valueOf(pieceNum);
            int bottleVal = Integer.valueOf(bottleNum);
            float finalprice = Float.valueOf(piecePrice);
            float money = pieceVal * finalprice + finalprice / model.goodsModuleInfo.hsgx * bottleVal;
            txtMoney.setText(FormatUtils.exactNumber(money, "0.00") + "元");
            txtPrice.setText("单价" + FormatUtils.exactNumber(finalprice/model.goodsModuleInfo.hsgx, "0.00")+"元");
        }else{
            txtMoney.setText("0.00元");
        }
    }

    /**
     * 控件的点击事件
     * @param view
     */
    @OnClick(value={R.id.dialog_fixsingleProduct_txtSpecial,R.id.dialog_fixsingleProduct_txtCancel,
            R.id.dialog_fixsingleProduct_txtOK,R.id.dialog_fixsingleProduct_imgClose,
            R.id.dialog_fixsingleProduct_txtPrice})
    public void onViewClick(View view){
        switch(view.getId()){
            case R.id.dialog_fixsingleProduct_txtSpecial://类型选择
                showGoodsTypeDialog();//显示商品类型选择框
                break;
            case R.id.dialog_fixsingleProduct_txtCancel://删除
                deleteGoodsFromShoppingCart(getContext(),dbUtils);//从购物车中删除该商品
                break;
            case R.id.dialog_fixsingleProduct_txtOK://确认修改
                fixOrderGoodsInformation();//修改商品订单信息
                break;
            case R.id.dialog_fixsingleProduct_imgClose://关闭窗口
                this.dismiss();
                break;
            case R.id.dialog_fixsingleProduct_txtPrice://修改单价
                showSinglePriceDialog();//显示单价修改提示框
                break;
        }

    }

    /**
     * 从购物车中删除该商品
     */
    public void deleteGoodsFromShoppingCart(final Context context,final DbUtils dbUtils){
        new AsyncTask<Void,Void,Void>(){
            private boolean isOk = true;
            private ProgressDialog dialog;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在删除...");
            }
            @Override
            protected Void doInBackground(Void... params) {
                try{
                    FworkDbHelper.deleteShoppingCartGoods(dbUtils, model.shoppingCartGoodsId);//删除商品购物车记录
                }catch (Exception e){
                    e.printStackTrace();
                    isOk = false;
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(isOk){
                    FixSingleProductDialog.this.dismiss();
                    Toast.makeText(getContext(), "删除订单商品成功!", Toast.LENGTH_SHORT).show();
                    if(listener!=null) listener.onValueChanged();//数据删除成功，通知Activity页面刷新数据
                }else{
                    Toast.makeText(getContext(),"删除订单商品失败!",Toast.LENGTH_SHORT).show();
                }
            }
        }.execute();
    }

    /**
     * 显示商品类型选择框
     */
    public void showGoodsTypeDialog(){
        new AlertDialog.Builder(getContext()).setItems(GoodsTypeConstant.GOODS_TYPE_SIMPLE_TEXTS,new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                txtSpecial.setText(GoodsTypeConstant.GOODS_TYPE_SIMPLE_TEXTS[which]);
                model.goodsType = GoodsTypeConstant.GOODS_TYPE_SIMPLE_VALUES[which];
                if(which!=0){
                    txtMoney.setText("0.00元");
                }else{
                    changeArguments();
                }
            }
        }).show();
    }

    /**
     * 显示单价修改提示框
     */
    public void showSinglePriceDialog(){
        double realPrice = model.goodsModuleInfo.dj/model.goodsModuleInfo.hsgx;//原单价
        double minPrice = Double.compare(SystemData.SaleManPower,0) == 0?realPrice:realPrice*SystemData.SaleManPower;//最小价格
        new FixPriceDialog(getContext(),realPrice,minPrice,new FixPriceDialog.OnPriceChangedListener() {
            @Override
            public void onPriceChange(double price) {
                txtPrice.setText("单价"+FormatUtils.exactNumber(price,"0.00")+"元");
                etPiecePrice.setText(FormatUtils.exactNumber(price*model.goodsModuleInfo.hsgx,"0.00"));
            }
        }).show();
    }

    /**
     * 修改商品订单信息
     */
    public void fixOrderGoodsInformation(){
        String pieceNum = ControlUtils.getNumberStringFromTextView(etPiece);
        String bottleNum = ControlUtils.getNumberStringFromTextView(etBottle);
        String picePrice = ControlUtils.getNumberStringFromTextView(etPiecePrice);
        model.pieceNum = Integer.valueOf(pieceNum);
        model.singleNum = Integer.valueOf(bottleNum);
        model.finalPrice = Float.valueOf(picePrice);
        model.noteInfomation = etSummary.getText().toString();//获取备注信息
        if((pieceNum.equals("0") && bottleNum.equals("0"))){
            Toast.makeText(getContext(),"请输入商品正确的数量值!",Toast.LENGTH_SHORT).show();
            return;
        }
        if(!checkSingleNum()||!isPiecePriceAvaliable()) return;//检测散数数量/检查价格数据/计算总金额
        model.totalMoney = !txtSpecial.getText().toString().equals("正常")?0:(model.finalPrice * model.pieceNum + model.finalPrice / model.goodsModuleInfo.hsgx * model.singleNum);
        model.goodsModuleInfo.dj = model.finalPrice;//修改商品的件价信息
        try {
            //做库存判断   如果购物数>库存数，提示是否继续购买？
            if(model.pieceNum*model.goodsModuleInfo.hsgx+model.singleNum>model.goodsInfo.kc-model.goodsInfo.xl
                    && SystemData.IsGoodsStockNotice == 1){//库存提示标识为1时提醒
                if(SystemData.saleMan.xdkcqx == 0){
                    Toast.makeText(getContext(),"当前库存量小于购买数量，不能修改商品信息!",Toast.LENGTH_SHORT).show();
                    return;
                }
                changeGoodsInfo();//改变商品信息
//                showOutofStockDialog();//显示超出库存的提示框
                return;
            }
            changeGoodsInfo();//改变商品信息
        }catch(Exception e){
            e.printStackTrace();
            Toast.makeText(getContext(),"修改订单商品失败!",Toast.LENGTH_SHORT).show();
        }
    }

//    /**
//     * 显示超出库存的提示框
//     */
//    public void showOutofStockDialog(){
//        final MessageBox msgBox = new MessageBox(getContext());
//        msgBox.setMessage("当前库存不足，确定继续选择该商品吗?");
//        msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                switch (v.getId()) {
//                    case MessageBox.ID_DIALOG_BUTTON_OK:
//                        msgBox.dismiss();
//                        try {
//                            changeGoodsInfo();
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                            Toast.makeText(getContext(), "修改订单商品失败!", Toast.LENGTH_SHORT).show();
//                        }
//                        break;
//                    case MessageBox.ID_DIALOG_BUTTON_CANCEL:
//                        msgBox.dismiss();
//                        break;
//                }
//            }
//        });
//        msgBox.show();
//    }

    /**
     * 改变商品信息
     */
    public void changeGoodsInfo()throws Exception{
        new AsyncTask<Void,Void,Void>(){
            private String errMessage;
            private ProgressDialog dialog;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(getContext(),"","正在提交数据...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    FworkDbHelper.saveShoppingCartGoods(dbUtils, model);
//                    dbUtils.update(model.goodsModuleInfo, WhereBuilder.b("sp_id", "=", model.goodsInfo.id), "dj");
                }catch (Exception e){
                    errMessage = e.getMessage();
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(errMessage!=null){
                    Toast.makeText(getContext(),"修改订单商品失败!",Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(getContext(),"修改订单商品成功!",Toast.LENGTH_SHORT).show();
                if(listener!=null) listener.onValueChanged();
                FixSingleProductDialog.this.dismiss();
            }
        }.execute();
    }

}
